package com.niannian.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import com.niannian.adapter.NumericWheelAdapter;
import com.niannian.adapter.OnWheelScrollListener;
import com.niannian.bean.GreetingNewsBean;
import com.niannian.dialog.YesNoDialog2;
import com.niannian.dialog.YesNoDialog2.onSimpleOnCancelListener;
import com.niannian.dialog.YesNoDialog2.onSimpleOnClicklListener;
import com.niannian.photo.AlbumActivity;
import com.niannian.photo.Bimp;
import com.niannian.photo.FileUtils;
import com.niannian.photo.GalleryActivity;
import com.niannian.photo.ImageItem;
import com.niannian.util.AsyncHandle;
import com.niannian.util.BitmapUtil;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MessageRecieveManager;
import com.niannian.util.MyDate;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.PlayerManager;
import com.niannian.util.Sys;
import com.niannian.util.UmengPage;
import com.niannian.util.VAR;
import com.niannian.view.CircleImageView;
import com.niannian.view.WheelView;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.MyApplication;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 
 * 发布
 * 
 * @author shengl
 * 
 */
public class PushRegardsActivity extends BaseActivity {

	public final static int FROM_push_news = 10;
	public final static int FROM_MIAN_PIC = 1;
	public final static int FROM_MIAN_TEXT = 2;
	public final static int FROM_MIAN_RECORD = 3;
	public final static int FROM_PUSH_REGARDS = 4;
	public final static int FROM_EDIT_REGARDS = 5;
	public final static int FROM_PUSH_REGARDS_CONFIRM_REPY = 6;// 对指定人回复问候
	public final static int FROM_PUSH_REGARDS_CONFIRM_AUD = 7;
	public final static int FROM_PUSH_REGARDS_CONFIRM = 8;// 对指定人发送问候
	// 问候
	LinearLayout ll_timeing;
	RelativeLayout ll_avatar_head;
	CircleImageView riv_sent_to_avatar, riv_sent_to_avatar_p;
	TextView tv_greeting_date_1, vt_sent_to_avatar_name;
	TextView tv_push_news_tip;

	// 语音部分
	LinearLayout ll_aud_exist;
	RelativeLayout rl_aud;
	ImageView iv_status_play;// 语音播放状态
	TextView tv_aud_len;// 语音时间
	TextView tv_afresh_record;// 重录语音
	ImageView iv_cancel;
	TextView tv_add_record;// 添加语音

	// 图片
	GridView noScrollgridview;
	GridAdapter picAdapter;

	private EditText et_content;

	String audPath = "";// 语音文件路径
	String pic = "";// 图片地址
	int aud_len = 0;// 语音时间
	String cTime = "";// 定时时间
	String cDate = "";// 定时日期
	String info = "";// 问候文字
	int uid = 0;// 问候接收人ID
	public static PushRegardsActivity instance;
	public final static int CHOOSE_CONTACT = 1;// 选择联系人
	int CHOOSE_CONTACT_FORM = 1;// 选择联系人来自那里，1表示来自家庭，2表示来自通讯录

	int sendType = 0;

	int rid = 0;// 编辑问候的 问候ID

	int reply_to = 0;// 回复发给那个人
	String phone = "";
	String name = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_push_regards);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		addActToGroup("push", this);
		initView();
		setLister();
		initTopView();
		initData();

		initMorePic();
		instance = this;
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title,tv_top_right;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("发问候");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);
		iv_top_right.setImageResource(R.drawable.send_e);
		tv_top_right= (TextView) findViewById(R.id.tv_top_right);
		tv_top_right.setVisibility(View.VISIBLE);
		tv_top_right.setText("发送");
		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				PlayerManager.getAudioPlayer(instance).playerPause();
				myfinish();
				Bimp.tempSelectBitmap.clear();
			}
		});

		tv_top_right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!Common.empty(et_content.getText().toString().trim()) || !Common.empty(audPath) || Bimp.tempSelectBitmap.size() > 0) {
					if (FROM_PUSH_REGARDS == sendType) {
						if (uid > 0 || phone.length() > 0) {
							sendOn();
						}
					} else {
						sendOn();
					}
				}
			}
		});

	}

	private void initView() {
		// 问候头像
		ll_avatar_head = (RelativeLayout) findViewById(R.id.ll_avatar_head);
		riv_sent_to_avatar = (CircleImageView) findViewById(R.id.riv_sent_to_avatar);// 发给那个人的头像
		riv_sent_to_avatar_p = (CircleImageView) findViewById(R.id.riv_sent_to_avatar_p);// 发给那个人的头像

		vt_sent_to_avatar_name = (TextView) findViewById(R.id.vt_sent_to_avatar_name);
		vt_sent_to_avatar_name.setVisibility(View.GONE);

		// 发送时间
		ll_timeing = (LinearLayout) findViewById(R.id.ll_timeing);
		tv_greeting_date_1 = (TextView) findViewById(R.id.tv_greeting_date_1);// 选择定时发送日期

		tv_push_news_tip = (TextView) findViewById(R.id.tv_push_news_tip);

		// 语音存在的时候
		ll_aud_exist = (LinearLayout) findViewById(R.id.ll_aud_exist);
		rl_aud = (RelativeLayout) findViewById(R.id.rl_aud);
		iv_status_play = (ImageView) findViewById(R.id.iv_status_play);
		tv_aud_len = (TextView) findViewById(R.id.tv_aud_len);
		tv_afresh_record = (TextView) findViewById(R.id.tv_afresh_record);
		iv_cancel = (ImageView) findViewById(R.id.iv_cancel);

		// 语音不存在
		tv_add_record = (TextView) findViewById(R.id.tv_add_record);// 添加语音

		et_content = (EditText) findViewById(R.id.et_content);// 文字内容

		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);

		et_content.addTextChangedListener(textWatcher);

	}

	private void initData() {
		Bundle b = getIntent().getExtras();

		sendType = b.getInt("from", 0);

		if (sendType == FROM_MIAN_PIC || sendType == FROM_MIAN_RECORD || sendType == FROM_MIAN_TEXT || sendType == FROM_push_news) {

			ll_avatar_head.setVisibility(View.GONE);
			ll_timeing.setVisibility(View.INVISIBLE);
			tv_push_news_tip.setVisibility(View.VISIBLE);
			noScrollgridview.setVisibility(View.VISIBLE);

			// aud_len = b.getInt("aud_len", 0);
			// audPath = b.getString("audPath");

			top_title.setText("发动态");

			if (sendType == FROM_MIAN_PIC) {
				// openActivity(AlbumActivity.class);
				// startAnimationLeftToRight();
			} else if (sendType == FROM_MIAN_TEXT) {
				getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
				et_content.setFocusable(true);
				et_content.setFocusableInTouchMode(true);
				et_content.requestFocus();
			} else if (sendType == FROM_MIAN_RECORD) {
				// openActivity(RecordActivity.class, FROM_MIAN_RECORD);
				// startAnimationLeftToRight();
				aud_len = b.getInt("time", 0);
				audPath = b.getString("savePath");

				if (aud_len > 0) {
					ll_aud_exist.setVisibility(View.VISIBLE);
					tv_add_record.setVisibility(View.GONE);
					tv_aud_len.setText(Common.showAudLen(aud_len));
					PlayerManager.getAudioPlayer(PushRegardsActivity.this).FromAudition(rl_aud, iv_status_play, audPath);

				} else {
					tv_add_record.setVisibility(View.VISIBLE);
					ll_aud_exist.setVisibility(View.GONE);
				}
				sendView();

			} else if (sendType == FROM_push_news) {

			}

		} else if (sendType == FROM_PUSH_REGARDS) {
			ll_avatar_head.setVisibility(View.VISIBLE);
			ll_timeing.setVisibility(View.VISIBLE);
			tv_push_news_tip.setVisibility(View.GONE);
			noScrollgridview.setVisibility(View.GONE);

			top_title.setText("发问候");

			tv_greeting_date_1.setText("立即发送");

		} else if (sendType == FROM_EDIT_REGARDS) {
			ll_avatar_head.setVisibility(View.VISIBLE);
			ll_timeing.setVisibility(View.VISIBLE);
			tv_push_news_tip.setVisibility(View.GONE);
			noScrollgridview.setVisibility(View.GONE);

			final GreetingNewsBean fdata = (GreetingNewsBean) b.get("fdata");
			rid = fdata.getId();
			aud_len = fdata.getAud_len();
			info = fdata.getInfo();
			audPath = fdata.getAud();
			noScrollgridview.setVisibility(View.GONE);
			et_content.setText(info + " ");
			et_content.setEnabled(false);
			top_title.setText("重设发送时间");

			et_content.setHintTextColor(getResources().getColor(R.color.col_b));
			et_content.setTextColor(getResources().getColor(R.color.col_b));

			MyApplication.finalbitmap.display(riv_sent_to_avatar, Common.getAvatarThumbs(fdata.getReceiver_avatar()));
			riv_sent_to_avatar.setEnabled(false);
			riv_sent_to_avatar_p.setEnabled(false);

			String date = Common.sgmdate2(fdata.getSent_time());
			cDate = date.split(" ")[0];
			cTime = date.split(" ")[1].substring(0, 5);
			uid = fdata.getReceiver();
			tv_greeting_date_1.setText(cDate + " " + cTime);

			tv_add_record.setVisibility(View.GONE);

			if (aud_len > 0) {
				ll_aud_exist.setVisibility(View.VISIBLE);
				tv_afresh_record.setVisibility(View.INVISIBLE);

				tv_aud_len.setText(Common.showAudLen(fdata.getAud_len()));

				rl_aud.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						PlayerManager.getAudioPlayer(PushRegardsActivity.this).FromNetAudition(rl_aud, iv_status_play, fdata.getAud());
					}
				});

			} else {
				ll_aud_exist.setVisibility(View.GONE);
			}

			// initDownloadVoice(fdata.getAud());
		} else if (sendType == FROM_PUSH_REGARDS_CONFIRM_REPY) {
			ll_avatar_head.setVisibility(View.VISIBLE);
			ll_timeing.setVisibility(View.VISIBLE);
			tv_push_news_tip.setVisibility(View.GONE);
			noScrollgridview.setVisibility(View.GONE);

			top_title.setText("发问候");
			tv_greeting_date_1.setText("立即发送");

			MyApplication.finalbitmap.display(riv_sent_to_avatar, Common.getAvatarThumbs(b.getString("avatar")));
			riv_sent_to_avatar.setEnabled(false);
			riv_sent_to_avatar_p.setEnabled(false);

			uid = b.getInt("uid", 0);
			reply_to = b.getInt("reply_to", 0);
		} else if (sendType == FROM_PUSH_REGARDS_CONFIRM) {
			ll_avatar_head.setVisibility(View.VISIBLE);
			ll_timeing.setVisibility(View.VISIBLE);
			tv_push_news_tip.setVisibility(View.GONE);
			noScrollgridview.setVisibility(View.GONE);

			top_title.setText("发问候");
			tv_greeting_date_1.setText("立即发送");

			MyApplication.finalbitmap.display(riv_sent_to_avatar, Common.getAvatarThumbs(b.getString("avatar")));
			riv_sent_to_avatar.setEnabled(false);
			riv_sent_to_avatar_p.setEnabled(false);

			uid = b.getInt("uid", 0);
		}

	}

	private void setLister() {

		riv_sent_to_avatar_p.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Bundle b = new Bundle();
				b.putInt("ACTION_TYPE", 1);
				openActivity(FamilyMemberActivity.class, b, CHOOSE_CONTACT);
				startAnimationLeftToRight();

			}
		});

		vt_sent_to_avatar_name.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Bundle b = new Bundle();

				b.putInt("ACTION_TYPE", 1);
				openActivity(FamilyMemberActivity.class, b, CHOOSE_CONTACT);
				startAnimationLeftToRight();
			}
		});

		tv_greeting_date_1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				initPopuwindow1();
			}
		});

		tv_add_record.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openActivity(RecordActivity.class, FROM_MIAN_RECORD);
				startAnimationLeftToRight();
			}
		});

		tv_afresh_record.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openActivity(RecordActivity.class, FROM_MIAN_RECORD);
				startAnimationLeftToRight();
			}
		});

		iv_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				audPath = "";
				aud_len = 0;
				tv_add_record.setVisibility(View.VISIBLE);
				ll_aud_exist.setVisibility(View.GONE);
				sendView();

			}
		});
	}

	private void sendOn() {

		info = et_content.getText().toString().trim();

		if (sendType == FROM_MIAN_PIC || sendType == FROM_MIAN_RECORD || sendType == FROM_MIAN_TEXT || sendType == FROM_push_news) {
			new PushFamilyNews().init(instance, null, true, "发送中...").execute();
		} else if (sendType == FROM_PUSH_REGARDS) {

			if (CHOOSE_CONTACT_FORM == 1) {
				new addRegard().init(instance, null, true, "发送中...").execute();
			} else {
				new getMembership().init(instance, null, true, "发送中...").execute();
			}

		} else if (sendType == FROM_EDIT_REGARDS) {
			new eidtRegard().init(instance, null, true, "提交中...").execute();
		} else if (sendType == FROM_PUSH_REGARDS_CONFIRM_REPY) {
			new replyRegard().init(instance, null, true, "发送中...").execute();
		} else if (sendType == FROM_PUSH_REGARDS_CONFIRM) {
			new addRegard().init(instance, null, true, "发送中...").execute();
		}

	}

	private MyTextWatcher textWatcher = new MyTextWatcher() {

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
		};

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			sendView();
		}
	};

	private void sendView() {

		if (!Common.empty(et_content.getText().toString().trim()) || !Common.empty(audPath) || Bimp.tempSelectBitmap.size() > 0) {
			if (FROM_PUSH_REGARDS == sendType) {
				if (uid > 0 || phone.length() > 0) {
					iv_top_right.setImageResource(R.drawable.send);
				} else {
					iv_top_right.setImageResource(R.drawable.send_e);
				}
			} else {
				iv_top_right.setImageResource(R.drawable.send);
			}
		} else {
			iv_top_right.setImageResource(R.drawable.send_e);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case CHOOSE_CONTACT:

			try {
				CHOOSE_CONTACT_FORM = data.getIntExtra("from", 1);
				if (CHOOSE_CONTACT_FORM == 1) {
					uid = data.getIntExtra("uid", 0);
					MyApplication.finalbitmap.display(riv_sent_to_avatar, Common.getAvatarThumbs(data.getStringExtra("avatar")));
					vt_sent_to_avatar_name.setVisibility(View.GONE);
					riv_sent_to_avatar.setVisibility(View.VISIBLE);
					riv_sent_to_avatar_p.setVisibility(View.VISIBLE);
				} else {
					phone = data.getStringExtra("phone");
					name = data.getStringExtra("name");
					vt_sent_to_avatar_name.setVisibility(View.VISIBLE);
					riv_sent_to_avatar.setVisibility(View.GONE);
					riv_sent_to_avatar_p.setVisibility(View.INVISIBLE);
					vt_sent_to_avatar_name.setText(name + "");

					if (name.length() > 0) {
						vt_sent_to_avatar_name.setText(name + "");
					} else {
						vt_sent_to_avatar_name.setText(phone + "");
					}
				}

			} catch (Exception e) {
				// TODO: handle exception
			}

			break;

		case VAR.TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9) {

				String fileName = String.valueOf(System.currentTimeMillis());
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				FileUtils.saveBitmap(bm, fileName);

				ImageItem takePhoto = new ImageItem();
				takePhoto.setBitmap(bm);
				Bimp.tempSelectBitmap.add(takePhoto);
			}
			break;

		case FROM_MIAN_RECORD:
			aud_len = data.getIntExtra("time", 0);
			audPath = data.getStringExtra("savePath");

			if (aud_len > 0) {
				ll_aud_exist.setVisibility(View.VISIBLE);
				tv_add_record.setVisibility(View.GONE);
				tv_aud_len.setText(Common.showAudLen(aud_len));
				PlayerManager.getAudioPlayer(PushRegardsActivity.this).FromAudition(rl_aud, iv_status_play, audPath);

			} else {
				tv_add_record.setVisibility(View.VISIBLE);
				ll_aud_exist.setVisibility(View.GONE);
			}
			sendView();

			break;

		default:
			break;
		}

	}

	PopupWindow PopupWindow1;

	@SuppressWarnings("deprecation")
	private void initPopuwindow1() {
		View mMenuView = null;
		hideSoftInputFromWindow();
		if (PopupWindow1 == null) {
			mMenuView = LayoutInflater.from(instance).inflate(R.layout.date1_popupwindow, null);

			TextView tv_date1_1 = (TextView) mMenuView.findViewById(R.id.tv_date1_1);
			TextView tv_date1_2 = (TextView) mMenuView.findViewById(R.id.tv_date1_2);
			TextView tv_date1_3 = (TextView) mMenuView.findViewById(R.id.tv_date1_3);
			TextView tv_date1_4 = (TextView) mMenuView.findViewById(R.id.tv_date1_4);

			tv_date1_2.setVisibility(View.GONE);
			tv_date1_3.setVisibility(View.GONE);
			tv_date1_1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					tv_greeting_date_1.setText("立即发送");
					// ll_greeting_date_2.setVisibility(View.INVISIBLE);

					cTime = MyDate.getDateHM();
					cDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
					PopupWindow1.dismiss();
				}
			});
			tv_date1_2.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Calendar old = Sys.StringToDate(cDate, "yyyy-MM-dd");
					int year = old.get(Calendar.YEAR);
					int month = old.get(Calendar.MONTH);
					int day = old.get(Calendar.DAY_OF_MONTH) + 1;
					cDate = String.format("%02d-%02d-%02d", year, month, day);
					tv_greeting_date_1.setText("明天");
					PopupWindow1.dismiss();

					// ll_greeting_date_2.setVisibility(View.VISIBLE);
				}
			});
			tv_date1_3.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Calendar old = Sys.StringToDate(cDate, "yyyy-MM-dd");
					int year = old.get(Calendar.YEAR);
					int month = old.get(Calendar.MONTH);
					int day = old.get(Calendar.DAY_OF_MONTH) + 2;
					cDate = String.format("%02d-%02d-%02d", year, month, day);
					tv_greeting_date_1.setText("后天");
					PopupWindow1.dismiss();

					// ll_greeting_date_2.setVisibility(View.VISIBLE);
				}
			});
			tv_date1_4.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					PopupWindow1.dismiss();
					// ll_greeting_date_2.setVisibility(View.VISIBLE);
					chooseDate();
				}
			});

			PopupWindow1 = new PopupWindow(mMenuView, mScreenWidth / 2, LayoutParams.WRAP_CONTENT, true);
			PopupWindow1.setBackgroundDrawable(new BitmapDrawable());
			PopupWindow1.setOutsideTouchable(true);
			PopupWindow1.setAnimationStyle(R.style.Popup_Animation_DownScale);
		} else {
			mMenuView = PopupWindow1.getContentView();
		}

		PopupWindow1.showAsDropDown(tv_greeting_date_1, -0, -0);

	}

	View chooseDate;
	private int year_start = 2014;
	private PopupWindow popupDate;

	private void chooseDate() {

		// TODO Auto-generated method stub
		chooseDate = LayoutInflater.from(instance).inflate(R.layout.year_month_day2, null);
		TextView title = (TextView) chooseDate.findViewById(R.id.wheel_title);
		final WheelView year = (WheelView) chooseDate.findViewById(R.id.wheel_year);
		final WheelView month = (WheelView) chooseDate.findViewById(R.id.wheel_month);
		final WheelView day = (WheelView) chooseDate.findViewById(R.id.wheel_day);

		title.setText("选择时间");
		String tm = tv_greeting_date_1.getText().toString();

		if (!"立即发送".equals(tm) && tm.length() > 0) {
			cDate = tm.split(" ")[0];
			cTime = tm.split(" ")[1].substring(0, 5);
		} else {
			cTime = MyDate.getDateHM();
			cDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
		}

		Calendar old = Sys.StringToDate(cDate, "yyyy-MM-dd");
		int tmp_year = old.get(Calendar.YEAR);
		int tmp_month = old.get(Calendar.MONTH) + 1;
		int tmp_day = old.get(Calendar.DAY_OF_MONTH);

		Calendar c = Calendar.getInstance();
		year_start = c.get(Calendar.YEAR);
		year.setAdapter(new NumericWheelAdapter(year_start, year_start + 5, "%02d", "年"));
		year.setCyclic(true);
		year.setCurrentItem(tmp_year - year_start);

		month.setAdapter(new NumericWheelAdapter(1, 12, "%02d", "月"));
		month.setCyclic(true);
		month.setCurrentItem(tmp_month - 1);

		day.setAdapter(new NumericWheelAdapter(1, c.getActualMaximum(Calendar.DAY_OF_MONTH), "%02d", "日"));
		day.setCyclic(true);
		day.setCurrentItem(tmp_day - 1);

		final WheelView hour = (WheelView) chooseDate.findViewById(R.id.wheel_hour);
		final WheelView minute = (WheelView) chooseDate.findViewById(R.id.wheel_minute);

		int tmp_hour = Integer.parseInt(cTime.split(":")[0]);
		int tmp_minute = Integer.parseInt(cTime.split(":")[1]);

		hour.setAdapter(new NumericWheelAdapter(0, 23, "%02d", "时"));
		hour.setCyclic(true);
		hour.setCurrentItem(tmp_hour);

		minute.setAdapter(new NumericWheelAdapter(0, 59, "%02d", "分"));
		minute.setCyclic(true);
		minute.setCurrentItem(tmp_minute);

		year.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				Calendar tmp = Calendar.getInstance();
				int _year_index = year.getCurrentItem();
				int _month_index = month.getCurrentItem();
				tmp.set(Calendar.YEAR, _year_index + year_start);
				tmp.set(Calendar.MONTH, _month_index);
				int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
				day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

				if (day.getCurrentItem() > _max_day_of_month - 1) {
					day.setCurrentItem(0);
				}
			}
		});

		month.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				Calendar tmp = Calendar.getInstance();
				int _year_index = year.getCurrentItem();
				int _month_index = month.getCurrentItem();
				tmp.set(Calendar.YEAR, _year_index + year_start);
				tmp.set(Calendar.MONTH, _month_index);
				int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
				day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

				if (day.getCurrentItem() > _max_day_of_month - 1) {
					day.setCurrentItem(0);
				}
			}
		});

		Button btn_ok = (Button) chooseDate.findViewById(R.id.btn_ok);
		btn_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int nYear = year.getCurrentItem() + year_start;
				int nMonth = month.getCurrentItem() + 1;
				int nDay = day.getCurrentItem() + 1;
				cDate = String.format("%02d-%02d-%02d", nYear, nMonth, nDay);
				tv_greeting_date_1.setText(cDate);

				int nHour = hour.getCurrentItem();
				int nMinute = minute.getCurrentItem();
				cTime = String.format("%02d:%02d", nHour, nMinute);

				tv_greeting_date_1.setText(cDate + " " + cTime);
				popupDate.dismiss();
			}
		});

		Button btn_cancel = (Button) chooseDate.findViewById(R.id.btn_cancel);
		btn_cancel.setVisibility(View.VISIBLE);
		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupDate.dismiss();
			}
		});

		popupDate = new PopupWindow(chooseDate, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popupDate.setBackgroundDrawable(new BitmapDrawable());
		popupDate.setAnimationStyle(R.style.ModePopupAnimation);
		popupDate.setOutsideTouchable(true);
		popupDate.setFocusable(true);

		popupDate.showAtLocation(tv_greeting_date_1, Gravity.CENTER, 0, 0);

	}

	private void hideSoftInputFromWindow() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_content.getWindowToken(), 0); // 强制隐藏键盘
	}

	protected class addRegard extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(instance, "发布问候失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {
					Common.tip(instance, "发布问候成功");
					MobclickAgent.onEvent(instance, UmengPage.ADD_REGARD_SUCCESS);

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = paramJSONObject.getJSONObject("data");
					jsonArray.put(jsonObject);
					databaseapi.updateGreetingReceive(userInfoManager.id, jsonArray, 12, "S", 0);
					openActivity(RegardsSendActivity.class);

					PlayerManager.getAudioPlayer(instance).playerPause();

					// if (CHOOSE_CONTACT_FORM == 2) {
					try {
						String smsData = paramJSONObject.getString("sms_content");
						if (!Common.empty(smsData)) {
							Uri uri = Uri.parse("smsto:" + phone);
							Intent it = new Intent(Intent.ACTION_SENDTO, uri);
							it.putExtra("sms_body", smsData);
							startActivity(it);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}

					// }
					destroyGroup("push");
					myfinish();
				} else {
					Common.tip(instance, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

		protected String runTask(Map<String, Object> paramMap) {
			if (CHOOSE_CONTACT_FORM == 1) {
				if ("立即发送".equals(tv_greeting_date_1.getText().toString().trim())) {
					return nnSyncApi.addRegard(uid, "S", info, null, audPath, aud_len, "", "", "", reply_to);
				} else {
					return nnSyncApi.addRegard(uid, "S", info, null, audPath, aud_len, cDate + " " + cTime + ":00", "", "", reply_to);
				}
			} else {
				if ("立即发送".equals(tv_greeting_date_1.getText().toString().trim())) {
					return nnSyncApi.addRegard(uid, "S", info, null, audPath, aud_len, "", phone, name, reply_to);
				} else {
					return nnSyncApi.addRegard(uid, "S", info, null, audPath, aud_len, cDate + " " + cTime + ":00", phone, name, reply_to);
				}
			}
		}
	}

	protected class replyRegard extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(instance, "回复问候失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {
					Common.tip(instance, "回复问候成功");
					MobclickAgent.onEvent(instance, UmengPage.ADD_REGARD_SUCCESS);

					databaseapi.updateReply(userInfoManager.id, paramJSONObject.getJSONObject("data"), "R", 0, reply_to, true);

					Intent intent = new Intent();
					intent.putExtra("id", reply_to);
					setResult(RESULT_OK, intent);
					PlayerManager.getAudioPlayer(instance).playerPause();

					try {
						String smsData = paramJSONObject.getString("sms_content");
						if (!Common.empty(smsData)) {
							Uri uri = Uri.parse("smsto:" + phone);
							Intent it = new Intent(Intent.ACTION_SENDTO, uri);
							it.putExtra("sms_body", smsData);
							startActivity(it);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}

					// }
					destroyGroup("push");
					myfinish();
				} else {
					Common.tip(instance, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

		protected String runTask(Map<String, Object> paramMap) {
			if ("立即发送".equals(tv_greeting_date_1.getText().toString().trim())) {
				return nnSyncApi.addRegard(uid, "S", info, null, audPath, aud_len, "", "", "", reply_to);
			} else {
				return nnSyncApi.addRegard(uid, "S", info, null, audPath, aud_len, cDate + " " + cTime + ":00", "", "", reply_to);
			}
		}
	}

	/**
	 * 上传家庭动态，上传成功之后更新本地数据库，并且通知动态显示列表显示数据
	 * 
	 * @author shengl
	 * 
	 */
	protected class PushFamilyNews extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(instance, "发送动态失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				MobclickAgent.onEvent(instance, UmengPage.ADD_POST_SUCCESS);
				JSONArray jsonArray = new JSONArray();
				JSONObject jsonObject = paramJSONObject.getJSONObject("data");
				int id = jsonObject.getInt("id");
				jsonArray.put(jsonObject);
				databaseapi.updateFamilyNews(userInfoManager.id, jsonArray, 12, "my");
				Common.tip(instance, "发送动态成功");
				Intent msgIntent = new Intent(MessageRecieveManager.FAMILY_NEWS_ADD_ACTION);
				msgIntent.putExtra("id", id);
				instance.sendBroadcast(msgIntent);

				destroyGroup("push");
				PlayerManager.getAudioPlayer(instance).playerPause();
				Bimp.tempSelectBitmap.clear();
				myfinish();
			} else {
				Common.tip(instance, ErrorCode.GetErrorMsg(retCode));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			List<NameValuePair> files = new ArrayList<NameValuePair>();
			for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {

				try {
					pic = MyApplication.FILE_PATH_TEMP + "nn" + ((new Date()).getTime() / 1000) + i + "pictemp.jpg";
					File file = new File(pic);
					if (file.exists()) {
						file.delete();
					}
					BitmapUtil.saveBmp(Bimp.tempSelectBitmap.get(i).getBitmap(), pic, 100);
					// BitmapUtil.saveBmp(BitmapUtil.getSmallBitmap(pic), pic,
					// 100);
					file = new File(pic);
					if (!file.exists()) {
						Common.tip(PushRegardsActivity.this, "图片保存失败");
					} else {
						if (i == 0) {
							files.add(new BasicNameValuePair("pic", pic));
						} else {
							files.add(new BasicNameValuePair("pic" + i, pic));
						}
					}

				} catch (Exception e) {
					Common.tip(PushRegardsActivity.this, "图片保存失败");
				}

			}

			if (!Common.empty(audPath)) {
				files.add(new BasicNameValuePair("aud", audPath));
			}

			// return nnSyncApi.posts(info, pic, audPath, aud_len);
			return nnSyncApi.posts(info, files, aud_len);
		}
	}

	protected class eidtRegard extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(instance, "提交失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = paramJSONObject.getJSONObject("data");
					jsonArray.put(jsonObject);
					databaseapi.updateGreetingReceive(userInfoManager.id, jsonArray, 12, "S", 0);

					PlayerManager.getAudioPlayer(instance).playerPause();

					String sent_time = jsonObject.getString("sent_time");
					int sent_time2 = Integer.parseInt(Common.getChangeTime(sent_time));
					Intent data = new Intent();
					data.putExtra("sent_time", sent_time2);
					data.putExtra("rid", rid);
					setResult(RESULT_OK, data);
					myfinish();
				} else {
					Common.tip(instance, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

		protected String runTask(Map<String, Object> paramMap) {

			if ("立即发送".equals(tv_greeting_date_1.getText().toString().trim())) {
				return nnSyncApi.eidtRegard(rid, "");
			} else {
				return nnSyncApi.eidtRegard(rid, cDate + " " + cTime + ":00");
			}

		}
	}

	protected class getMembership extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(instance, "获取失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {

					int ship = paramJSONObject.getInt("ship");
					if (ship == 1) {
						new addRegard().init(instance, null, true, "发送中...").execute();
					} else {
						initDialog(ship);
					}

				} else {
					Common.tip(instance, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.getMembership(userInfoManager.id, phone);

		}
	}

	YesNoDialog2 tip;

	private void initDialog(int ship) {
		if (ship == -1) {
			tip = new YesNoDialog2(instance, "当前问候接收人尚未注册, 继续发送将自动为该接收人注册咚咚账号,并需要你以短信通知Ta, 以便及时收听问候.  是否继续?");
		} else {
			tip = new YesNoDialog2(instance, "当前问候接收人不在你的亲友列表, 是否继续发送?");

		}
		tip.setConfimButtonText("继续");
		tip.setOnCancelListener(new onSimpleOnCancelListener() {

			@Override
			public void onCancel() {
				tip.dismiss();
			}
		});
		tip.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {
				new addRegard().init(instance, null, true, "发送中...").execute();
				tip.dismiss();
			}
		});
		tip.show();
	}

	private void initMorePic() {

		if (sendType != FROM_MIAN_PIC) {
			Bimp.tempSelectBitmap.clear();
		}
		// noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		picAdapter = new GridAdapter(this);
		picAdapter.update();
		noScrollgridview.setAdapter(picAdapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					Log.i("ddddddd", "----------");
					// initListDialog();
					openActivity(AlbumActivity.class);
					startAnimationLeftToRight();

				} else {
					Intent intent = new Intent(instance, GalleryActivity.class);
					intent.putExtra("position", "1");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if (Bimp.tempSelectBitmap.size() == 9) {
				return 9;
			}
			return (Bimp.tempSelectBitmap.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.p_item_published_grida, parent, false);
				holder = new ViewHolder();
				holder.ll_pic = (LinearLayout) convertView.findViewById(R.id.ll_pic);
				holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);

				int pich = (int) ((BaseActivity.mScreenWidth / 3) - Common.dip2px(PushRegardsActivity.this, 20));
				android.view.ViewGroup.LayoutParams params = holder.image.getLayoutParams();
				params.height = pich;
				params.width = pich;
				holder.image.setLayoutParams(params);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.tempSelectBitmap.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
			public LinearLayout ll_pic;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					picAdapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			Bimp.max = Bimp.tempSelectBitmap.size();
			picAdapter.notifyDataSetChanged();
			// new Thread(new Runnable() {
			// public void run() {
			// while (true) {
			// if (Bimp.max == Bimp.tempSelectBitmap.size()) {
			// Message message = new Message();
			// message.what = 1;
			// handler.sendMessage(message);
			// break;
			// } else {
			// Bimp.max += 1;
			// Message message = new Message();
			// message.what = 1;
			// handler.sendMessage(message);
			// }
			// }
			// }
			// }).start();
		}
	}

	@Override
	public void onBackPressed() {
		PlayerManager.getAudioPlayer(instance).playerPause();
		Bimp.tempSelectBitmap.clear();
		myfinish();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		picAdapter.update();

		sendView();
	}
}
